#!/usr/bin/env python

import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

from django.utils import simplejson

from model import ClassState
from model import Lecture
from model import Topic


class MyHandler(webapp.RequestHandler):
    
    def get(self):
        lecture = Lecture.get(self.request.get('lectureKey'))
        classState = db.Query(ClassState).filter('lecture = ', lecture).get()
        
        if not classState:
            self.response.out.write(simplejson.dumps(False))
            return
        
        topicKey = self.request.get('topicKey')
        if topicKey == 'end':
            classState.ended = True
            topic = None
        else:
            classState.ended = False
            topic = Topic.get(topicKey)

        classState.currentTopic = topic
        classState.put()

        self.response.out.write(True)
              
def main():
    app = webapp.WSGIApplication([
        (r'.*', MyHandler)], debug=True)
    wsgiref.handlers.CGIHandler().run(app)

if __name__ == "__main__":
    main()